<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2015/2/6
 * File: Database.php
 */
namespace ulue\core\db\mysql\command;

use ulue\core\db\base\command\AbstractDatabase;
use ulue\core\db\base\schema\Schema;
use ulue\core\db\mysql\query\SqlBuilder;
use ulue\core\db\mysql\driver\MysqlDriver;

class Database extends AbstractDatabase
{
    /**
     * @var MysqlDriver
     */
    protected $db;

    public function select()
    {
        $this->db->exec('USE ' . $this->qn($this->name));

        return $this;
    }

    public function create($ifNotExists = false, array $options = [])
    {
        $default = [
            'charset' => 'utf8',
            'collate' => 'utf8_general_ci',
        ];

        if ($ifNotExists) {
            $sql = "CREATE DATABASE `{$this->name}`";
        }
    }

    public function drop($ifNotExists = false)
    {
        # code...
    }

    public function rename($newName, $returnNew = true)
    {

    }

    // @todo ？？？？
    public function setCharset($charset='utf8')
    {
        $this->db->exec('SET NAMES '.$charset);

        return $this;
    }


    //得到当前数据库中所有的表名
    public function getTableNames($refresh=false)
    {

        if (!$this->_tbNames || $refresh)
        {
            $sql    = SqlBuilder::showDbTables($this->name);
            $result = $this->db->setSql($sql)->queryAll();

            foreach($result as $v)
            {
                $this->_tbNames[] = $v["Tables_in_{$this->name}"];
            }

            \Debug::trace("首次获取数据库[{$this->name}]的所有表名",['TableNames'=>$this->_tbNames]);
        }

        return $this->_tbNames;
    }

    /**
     * getTableDetails
     * @return  array[]
     */
    public function getTableDetails()
    {
        if (!$this->_tbDetails)
        {
            $query   = SqlBuilder::showDbTableStatus($this->name);
            $details = $this->db->setSql($query)->queryAll('Name');

            $this->_tbNames = array_keys($details);

            \Debug::trace("首次获取数据库[{$this->name}]中所有表的详情信息",['TableDetails'=>$this->_tbDetails]);
        }

        return $this->_tbDetails;
    }

    /**
     * @param string $table
     * @param bool $refresh
     * @throws \DInvalidArgumentException
     * @return Table
     */
    public function getTableDetail($table, $refresh=false)
    {
        if (!$table)
        {
            throw new \DInvalidArgumentException('请传入要查询获取的表名！');
        }

        if ( !isset($this->_tbDetails[$table]) )
        {

            $query = SqlBuilder::showDbTableStatus($this->name, 'Name = ' . $this->q($table));

            $detail = $this->db->setSql($query)->queryOne();

            if (!$detail)
            {
                return false;
            }

            $this->_tbDetails[$table] = $detail;

            \Debug::trace("首次获取数据库[{$this->name}]中[{$table}]表的详情信息",
                [ $table.' Table Detail' => $this->_tbDetails[$table] ]
                );
        }

        return $this->_tbDetails[$table];
    }

    /**
     * @param $table
     * @return Table
     * @throws \DInvalidArgumentException
     */
    public function getTable($table)
    {
        if (!$table)
        {
            throw new \DInvalidArgumentException('请传入要查询获取的表名！');
        }

        $class = sprintf('\ulue\core\db\%s\command\Table', $this->db->name);
        $key   = md5($class.$table);

        if (!isset($this->_tbs[$key]))
        {
            $this->_tbs[$key]  = new $class($table, $this->db);

            \Debug::trace("首次获取数据库[{$this->name}]中[{$table}]表的操作实例");
        }

        return $this->_tbs[$key];
    }

    /**
     * @param string $table
     * @return Schema
     */
    public function getTableSchema($table)
    {
        return $this->getTable($table)->getSchema();
    }

    public function tableExists($name)
    {
        return (bool)$this->getTableDetail($name);
    }

}// end class Database